package com.szgz.platform.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@MappedTypes(Set.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class SetTypeHandler extends BaseTypeHandler<Set<?>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Set<?> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            // 将Set中的元素转换为JSON数组格式，支持任何类型的Set
            String value = parameter.stream()
                    .map(Object::toString)
                    .map(s -> "\"" + s + "\"")
                    .collect(java.util.stream.Collectors.joining(",", "[", "]"));
            ps.setString(i, value);
        } else {
            ps.setString(i, "[]");
        }
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return parseJsonArray(value);
    }

    @Override
    public Set<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return parseJsonArray(value);
    }

    @Override
    public Set<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return parseJsonArray(value);
    }
    
    private Set<String> parseJsonArray(String value) {
        if (value == null || value.trim().isEmpty() || "[]".equals(value.trim())) {
            return new HashSet<>();
        }
        
        try {
            // 简单的JSON数组解析，移除方括号和引号，按逗号分割
            String cleanValue = value.trim();
            if (cleanValue.startsWith("[") && cleanValue.endsWith("]")) {
                cleanValue = cleanValue.substring(1, cleanValue.length() - 1);
            }
            
            if (cleanValue.trim().isEmpty()) {
                return new HashSet<>();
            }
            
            return Arrays.stream(cleanValue.split(","))
                    .map(String::trim)
                    .map(s -> s.replace("\"", ""))
                    .filter(s -> !s.isEmpty())
                    .collect(java.util.stream.Collectors.toSet());
        } catch (Exception e) {
            // 如果解析失败，返回空集合
            return new HashSet<>();
        }
    }
}
